#!/bin/bash
set -x
local_ip=$(hostname -i|awk '{print $1}')

# 创建分片集群
echo 'config = {
"_id":"pcloud_core", "members":[
{"_id":0,"host":"172.31.4.11:27017"},{"_id":1,"host":"172.31.4.12:27017"},{"_id":2,"host":"172.31.4.13:27017"}
]
}; rs.initiate(config)' | /usr/bin/mongosh --host localhost:27017 admin

sleep 20
# 找到主节点
primary=$(/usr/bin/mongosh --host localhost:27017 admin -eval "db.hello().primary" |tail -1);echo $primary


if [ "$primary" == "${local_ip}:27017" ];then
    # 创建用户并授权 # 数据库初始化
    echo 'db.createUser({ user: "pcloud", pwd: "pcloudcore123", roles: [ { role: "root", db: "admin" } ] })' | /usr/bin/mongosh --host localhost:27017 admin
    /usr/bin/mongosh "mongodb://pcloud:pcloudcore123@172.31.4.11:27017,172.31.4.12:27017,172.31.4.13:27017/pcloud_core?replicaSet=pcloud_core&authSource=admin" /init/pcloud_core_init.js &&\
    sleep 10 &&\
    /usr/bin/mongosh "mongodb://pcloud:pcloudcore123@172.31.4.11:27017,172.31.4.12:27017,172.31.4.13:27017/pcloud_core?replicaSet=pcloud_core&authSource=admin" /init/pcloud_init_dashboard.js
    exit 0
else
    exit 1
fi